<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2006/03/23 01:49:40 $)
// $RCSfile: modify_step2.php,v $ : $Revision: 1.4 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================

if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

if ($dbCore->connected)
{
	$userData = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."staff` WHERE `username` = '". addslashes($_REQUEST["username"]) ."' AND `password` = '". addslashes(md5($_REQUEST["password"])) ."';");

	if ($userData["username"] == $_REQUEST["username"] && trim($userData["username"]) != "")
	{
		// Now get the registered modules
		$registeredmodules = array();
		$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."settings` WHERE `section` = 'registeredmodules';");
		while ($dbCore->nextRecord())
		{
			$registeredmodules[] = $dbCore->Record["vkey"];
		}
		// Add core module, its not registered anywhere
		$registeredmodules[] = "core";

		if (!is_array($registeredmodules))
		{
			$_SWIFT["error"] = true;
			$_SWIFT["errormsg"] = "Invalid Settings Table, Upgrade Wizard was unable to recover from this error, Please contact support";
		} else {

			if ($_POST["page"] == "-1")
			{
				require_once ("./includes/functions_settings.php");
				require_once ("./includes/functions_template.php");
				rebuildSettingsCache();

				if ($handle = opendir('./cache/')) {
					while (false !== ($file = readdir($handle))) { 
						if ($file != "." && $file != ".." && $file != "index.html") { 
							@unlink("./cache/".$file); 
						}
					}
					closedir($handle); 
				}

				$result = updateTemplatesFromFile(dirname(__FILE__)."/../includes/swift.templates.xml", false, false);
				if (!$result)
				{
					trigger_error("ERROR: Could not insert all templates. $sqlcount - $insertedchunks", E_USER_ERROR);
				}

				header("location: modify.php?username=". urlencode($_REQUEST["username"]) ."&password=". urlencode($_REQUEST["password"]) ."&step=2");
				exit;
			}

			foreach ($_SETUP["modules"] as $key=>$val)
			{
				require_once ("./modules/".cleanVar($val)."/setup.php");
			}

			// ======= INSTALL =======
			if ($_REQUEST["action"] == "install" && !empty($_REQUEST["setupmodule"]))
			{
				if (in_array($_REQUEST["setupmodule"], $_SETUP["modules"]) && is_numeric($_REQUEST["page"]))
				{
					$modulename = cleanVar($_REQUEST["setupmodule"]);
					$_SWIFT["processbuttons"] = true;
					$_SWIFT["action"] = "install";

					displayHeader();
					// Get total number of pages for this module, the _swift_install should be declared in module setup file
					eval("\$moduletotalpages = _". cleanVar(trim($modulename)) ."_install(\"getpages\");");

					// Display Current Page etc
					displayMessage("Module: $modulename (Page ". $_REQUEST["page"] ." of $moduletotalpages)");

					// Build the query for this very page
					eval("_". cleanVar(trim($modulename)) ."_install(\"buildpage\", \$_REQUEST[\"page\"]);");

					// Execute the queries
					execAllQueries();

					// Calculate next step page
					if ($_REQUEST["page"] >= $moduletotalpages)
					{
						$_SWIFT["execpage"] = "-1";
					} else {
						// We are not more than it yet, increment it
						$_SWIFT["execmodule"] = $modulename;
						$_SWIFT["execpage"] = $_REQUEST["page"]+1;
					}
					displayFooter();
					exit;
				} else {
					trigger_error(sprintf("Setup failed, %s module does not exist", $_POST["setupmodule"]), E_USER_ERROR);
				}
			}

			// ======= UNINSTALL =======
			if ($_GET["action"] == "uninstall" && !empty($_GET["module"]))
			{
				$modulename = cleanVar($_GET["module"]);
				$_SWIFT["processbuttons"] = true;
				$_SWIFT["execpage"] = "-1";

				displayHeader();

				call_user_func("_". $modulename ."_uninstall");
				execAllQueries();

				displayFooter();
				exit;
			}

			// ======= UPGRADE =======
			if ($_GET["action"] == "upgrade" && !empty($_GET["module"]))
			{
				$modulename = cleanVar($_GET["module"]);
				$_SWIFT["processbuttons"] = true;
				$_SWIFT["execpage"] = "-1";

				displayHeader();

				call_user_func("_". $modulename ."_upgrade");
				execAllQueries();

				displayFooter();
				exit;
			}

			if (empty($_REQUEST["action"]))
			{
			displayHeader();
			?>
			<table width="400"  border="0" cellspacing="0" cellpadding="3">
			<?
			foreach ($_SETUP["modules"] as $key=>$val)
			{
				?>
				<tr>
				<td width="100" align="left" valign="top"><span class="mediumtext"><?=$val?></span></td>
				<td align="right" valign="top"><input <?
				if (in_array($val, $registeredmodules) || $val == "core") {
					echo 'DISABLED class="disabledbutton"';
				} else {
					echo 'class="inputbuttonred" onClick="javascript:parent.location=\'modify.php?action=install&setupmodule='.$val.'&username='.urlencode($_REQUEST["username"]) .'&password='.urlencode($_REQUEST["password"]).'&step=2&page=1\';"';
				}
				?> type="button" name="install" value="Install">&nbsp;<input <?
				if (!in_array($val, $registeredmodules) || $val == "core") {
					echo 'DISABLED class="disabledbutton"';
				} else {
					echo 'class="inputbutton" onClick="javascript:parent.location=\'modify.php?action=uninstall&module='.$val.'&username='.urlencode($_REQUEST["username"]) .'&password='.urlencode($_REQUEST["password"]).'&step=2\';"';
				}
				?> type="button" name="uninstall" value="Uninstall">&nbsp;<input <?
				if (in_array($val, $registeredmodules) && function_exists("_".$val."_upgrade")) {
					echo 'class="inputbutton" onClick="javascript:parent.location=\'modify.php?action=upgrade&module='.$val.'&username='.urlencode($_REQUEST["username"]) .'&password='.urlencode($_REQUEST["password"]).'&step=2\';"';
				} else {
					echo 'DISABLED class="disabledbutton"';
				}
				?> type="button" name="upgrade" value="Upgrade">&nbsp;</td>
				</tr>
				<?
			}
			?>
			</table>
			<?
			displayFooter();
			}
		}
	} else {
		$_POST["step"] = "1";
		$_SWIFT["errormsg"] = true;
		$_SWIFT["errormsg"] = "Invalid Username or Password";
	}
} else {
	$_SWIFT["error"] = true;
}
?>